package com.sniper.springmvc.config;

import com.sniper.springmvc.datasource.DataSourceRouter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建sqlSessionFactoryBean 实例
 * http://www.cnblogs.com/Alandre/p/6611813.html
 * Created by suzhen on 2017/4/14.
 */
@Configuration
public class SessionFactoryConfig implements TransactionManagementConfigurer {

    static final String MYBATIS_CONFIG = "mybatis-config.xml";

    @Autowired
    DataSource dataSource;

    @Autowired
    DataSource slaveDataSource;


    static final String typeAliasPackage = "com.sniper.springmvc.model";
    static final String MAPPER_LOCATION = "classpath*:mapping/*.xml";

    /**
     * @return
     */
    @Primary
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory createSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(getDataSourceRouter());
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory factory) throws Exception {
        return new SqlSessionTemplate(factory);
    }

    /**
     * 多数据源
     *
     * @return
     */
    @Bean
    public DataSourceRouter getDataSourceRouter() {
        DataSourceRouter sourceRouter = new DataSourceRouter();
        sourceRouter.setDefaultTargetDataSource(dataSource);
        Map<Object, Object> dataSources = new HashMap<>();
        dataSources.put("master", dataSource);
        dataSources.put("salve", dataSource);
        sourceRouter.setTargetDataSources(dataSources);
        return sourceRouter;
    }

    @Bean
    @Primary
    @Override
    public DataSourceTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(getDataSourceRouter());
    }
}
